﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Main
{
    class HttpRequest
    {

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受   
        }


        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, Encoding charset)
        {
            HttpWebRequest request = null;
            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = HttpWebRequest.Create(url) as HttpWebRequest;
            //request.ProtocolVersion = HttpVersion.Version11;
            request.KeepAlive = false;
            request.Timeout = 5000;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.AllowWriteStreamBuffering = false;

            //如果需要POST数据   
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                //byte[] data = charset.GetBytes(buffer.ToString());
                string postData = buffer.ToString();
                request.ContentLength = postData.Length;

                StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
                writer.Write(buffer);
                writer.Flush();
            }
            return request.GetResponse() as HttpWebResponse;
        }

        public static HttpWebResponse CreateGetHttpResponse(string url)
        {
            HttpWebRequest request = null;
            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = HttpWebRequest.Create(url) as HttpWebRequest;
            //request.ProtocolVersion = HttpVersion.Version11;
            request.KeepAlive = false;
            request.Timeout = 5000;
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.AllowWriteStreamBuffering = false;

            return request.GetResponse() as HttpWebResponse;
        }

    }
}
